package com.miao.sso.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.miao.sso.entity.TbUser;
import com.miao.sso.service.TbUserService;
import com.miao.sso.service.impl.TbUserServiceImpl;
import com.miao.sso.web.cookie.CookieUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RequestMapping("/user")
@Controller
public class UserController {


    private static final String COOKIE_NAME="TT_TOKEN";


    @Autowired
    private TbUserServiceImpl tbUserService;

    @Autowired
    private TbUserService userService;

    /**
     * 注册
     * @return
     */
    @RequestMapping(value ="register",method = RequestMethod.GET)
    public String register(){
        return "register";
    }


    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "doLogin",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> doLogin(TbUser tbUser, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> result=new HashMap<>();
        try{
            String token = tbUserService.doLogin(tbUser.getUsername(), tbUser.getPassword());
            if(token==null){
                //登录失败
                result.put("status",500);
                return result;
            }
            //登录成功！保存到cookie中
            result.put("status",200);
            CookieUtils.setCookie(request,response,COOKIE_NAME,token);
        }catch (Exception e){
            e.printStackTrace();
            //登录失败
            result.put("status",500);
            return result;
        }
        return result;
    }

    /**
     * 验证数据是否可用
     * @return
     */
    @RequestMapping(value = "{param}/{type}",method =RequestMethod.GET )
    public ResponseEntity<Boolean> check(@PathVariable("param")String param,@PathVariable("type") Integer type) {
        try{
            Boolean bool = tbUserService.chech(param, type);
            if(bool==null){
                //参数有误
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }
            //兼容
            return ResponseEntity.ok(!bool);
        }catch (Exception e){
          e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     * 注册
     * @Validated数据校验 1导入依赖，2.添加校验，3判断校验
     * @return
     */
    @RequestMapping(value = "doRegister",method = RequestMethod.POST)
    @ResponseBody
    public  Map<String,Object> doRegister(@Validated TbUser tbUser , BindingResult bindingResult){
        Map<String,Object> result=new HashMap<>();
        //判断是否通过校验
        if(bindingResult.hasErrors()){
          //没有通过校验
            result.put("status","400");
            //循环获取数据校验中的错误信息
            List<String> msg=new ArrayList<>();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError:allErrors){
                String message = objectError.getDefaultMessage();
                msg.add(message);
            }
            result.put("data","参数有误！"+StringUtils.join(msg,'|'));
            return result;
        }
        try{
            tbUser.setId(null);
            tbUser.setCreated(new Date());
            tbUser.setUpdated(tbUser.getCreated());
            //密码加密处理MD5
            tbUser.setPassword(DigestUtils.md5Hex(tbUser.getPassword()));
            boolean bool = this.userService.insert(tbUser);
            if(bool){
                //业务状态码
                result.put("status","200");
            }else {
                result.put("status","500");
                result.put("data","注册失败！请重新注册！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("status","500");
            result.put("data","注册失败！请重新注册！");
        }
       return result;
    }

    /**
     * 查询用户信息
     * @param token
     * @return
     */
    @RequestMapping(value = "{token}",method = RequestMethod.GET)
    public ResponseEntity<TbUser> queryUserByToken(@PathVariable("token") String token) {

        try {
            TbUser user = tbUserService.queryUserByToken(token);
            if (null == user) {
                //不存在
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}
